//
//  HJNetworkTools.swift
//  01 swift中网络框架的封装
//
//  Created by zhangmi on 16/5/23.
//  Copyright © 2016年 Paramount Pictures. All rights reserved.
//

import UIKit
//导入命名空间
import AFNetworking

//声明枚举
//枚举任意类型
enum HTTPMethods: Int {
    case POST
    case GET
}

struct API {
    
    static let hostName = "https://api.weibo.com/"
//    static let hostName = "https://dev.api.weibo.com/"
    //加载用户的token
    static let loadAccessToken = "oauth2/access_token"
    //加载用户信息
    static let loaduserInfo = "2/users/show.json"
    
    //加载首页数据
    static let loadHomeData = "2/statuses/home_timeline.json"
    
    //发布微博
    static let sendStatus = "2/statuses/update.json"
    
    //发布微博图片
    static let sendImageStatus = "https://upload.api.weibo.com/2/statuses/upload.json"
}

class HJNetworkTools: AFHTTPSessionManager {
    //声明单例对象
    static let sharedTools: HJNetworkTools = {
        //把url前面的一样的部分, 声明为基础的url地址
        //把url前面一样的部分, 声明为基础的url地址
        let url = NSURL(string: API.hostName)
        let tools = HJNetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")

        return tools
    }()
    
    
    //封装get和post请求
    /*
     tools.GET(<#T##URLString: String##String#>, parameters: <#T##AnyObject?#>, success: <#T##((NSURLSessionDataTask, AnyObject?) -> Void)?##((NSURLSessionDataTask, AnyObject?) -> Void)?##(NSURLSessionDataTask, AnyObject?) -> Void#>, failure: <#T##((NSURLSessionDataTask?, NSError) -> Void)?##((NSURLSessionDataTask?, NSError) -> Void)?##(NSURLSessionDataTask?, NSError) -> Void#>)
     */
    
    
    func request(method: HTTPMethods,urlString: String, parameters: AnyObject?,finished: (responseObject: AnyObject?, error: NSError?) -> () ) {
        
        //定义闭包参数 将相同的闭包当做参数传递
        let success = { (task: NSURLSessionDataTask, result: AnyObject?) -> () in
            //执行请求成功的回调
            finished(responseObject: result, error: nil)
        }
        
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> () in
            //执行失败的回调
            print(error)
            finished(responseObject: nil, error: error)
        }
        
        if method == .GET {
            
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            //            // "_" 表示忽略
            //            GET(urlString, parameters: parameters, progress: nil, success: { (_, result) in
            //                //执行请求成功的回调
            //                finished(responseObject: result, error: nil)
            //                }, failure: { (_, error) in
            //                    //执行失败的回调
            //                    finished(responseObject: nil, error: error)
            //            })
        } else {
            
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            //            POST(urlString, parameters: parameters, progress: nil, success: { (_, result) in
            //                //执行请求成功的回调
            //                finished(responseObject: result, error: nil)
            //                }, failure: { (_, error) in
            //                    //执行失败的回调
            //                    finished(responseObject: nil, error: error)
            //            })
        }
    }
    
}

///MARK: 将用户认证 获取用户信息相关的方法归到这个分类里面
extension HJNetworkTools {
    //请求用户的token
    func loadAccessToken(code: String, finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        let parameters = ["client_id" : client_id, "client_secret":client_secret, "grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
        //调用封装的核心方法
        request(.POST, urlString: API.loadAccessToken, parameters: parameters, finished: finished)
    }
    
    //加载用户信息
    func loadUserInfo(response: [String : AnyObject],finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        
        //用户访问接口权限的标识
        let token = response["access_token"]!
        let uid = response["uid"]!
        
        //字典中可以添加 nil嘛
        let parameters = ["access_token": token, "uid": uid]
        request(.GET, urlString: API.loaduserInfo, parameters: parameters, finished: finished)
    }
}


//首页相关
extension HJNetworkTools {
    
    func loadHomePageData(since_id: Int64,max_id: Int64, finished: (responseObject: AnyObject?, error: NSError?) -> ()) {

        guard let token = HJUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        var parameters = ["access_token": token,"count":"10"]
        if since_id > 0 {
            //添加since_id到参数中
            parameters["since_id"] = "\(since_id)"
            
        }
        if max_id > 0 {
            //会有bug 会返回max_id 对应的微博
            parameters["max_id"] = "\(max_id)"
        }

        request(.GET, urlString: API.loadHomeData, parameters: parameters, finished: finished)
    }
    
}

extension HJNetworkTools {
//    func sendStatus(status: String,finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
    
    //发布微博文本 && 发布微博图片
    func sendStatus(status: String,images: [UIImage],finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        guard let token = HJUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        
        let parameters = ["access_token": token,"status":status]
//        request(.POST, urlString: API.sendStatus, parameters: parameters, finished: finished)
        if images.count > 0 {
            //图片微博  图片上传  AFN已经封装好AFN上传方法 使用POST方法
            let imageData = UIImagePNGRepresentation(images.first!)!
            self.POST(API.sendImageStatus, parameters: parameters, constructingBodyWithBlock: { (formdata) in
                //将上传的二进制数据添加到formdata中
                /*
                 1.data          需要上传的二进制数据
                 2.name          服务器接收的字段
                 3.fileName      服务器存储的上传文件的名称  但是这个地方可以随便去  新浪微博服务器会自己根据自己的规则命名
                 4.mimeType      上传的文件的类型  application/octet-stream 忽略文件类型
                 */
                
                formdata.appendPartWithFileData(imageData, name: "pic", fileName: "ococooc", mimeType: "application/octet-stream")
                }, progress: nil, success: { (_, result) in
                    finished(responseObject: result, error: nil)
                }, failure: { (_, error) in
                    finished(responseObject: nil, error: error)
            })
            
            
        } else {
            //文本微博
            request(.POST, urlString: API.sendStatus, parameters: parameters, finished: finished)
        }
        
    }

}





